﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using com.pro2e.console.service.auth.dao;
using com.pro2e.console.service.auth.vo;

/// <summary>
/// CustomSqlMembershipProvider 的摘要描述
/// </summary>
/// 
namespace com.pro2e.console.service.auth
{
    public class CustomHBNMembershipProvider : MembershipProvider
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(CustomHBNMembershipProvider));
        private LoginUserDao loginUserDao = new LoginUserDao();

        public override MembershipUser CreateUser(string username, string
             password, string email, string passwordQuestion, string
             passwordAnswer, bool isApproved, object providerUserKey,
             out MembershipCreateStatus status)
        {

            //check if username was existed
            LoginUser user = null;
            MembershipUser newUser = null;

            if ((user = loginUserDao.DaoGetVOById<LoginUser>(username)) != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return newUser;
            }
            else if (!string.IsNullOrEmpty(email)&&email.Equals(user.Email))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return newUser;
            }
            else
            {
                user = new LoginUser();
                user.Email = email;
                user.CreateDate = DateTime.Now;
                if (!string.IsNullOrEmpty(email)) 
                {
                    user.LoweredEmail = email.ToLower();
                }
                
                user.Password = password;
                user.PasswordAnswer = passwordAnswer;
                user.PasswordQuestion = passwordQuestion;
                user.IsApproved = isApproved;
                user.UserId = username;
                user.CreateDate = DateTime.Now;
                user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                user.FailedPasswordAttemptWindowStart = DateTime.Now;
                user.LastLockoutDate = DateTime.Now;
                user.LastLoginDate = DateTime.Now;
                user.LastPasswordChangedDate = DateTime.Now;
                user.PasswordFormat = 0;
                user.PasswordSalt = "";
                user.FailedPasswordAnswerAttemptCount = 0;
                user.FailedPasswordAttemptCount = 0;
               

                try
                {
                    loginUserDao.DaoInsert(user);
                    newUser = new MembershipUser(
                   "CustomHBNMembershipProvider",
                   username, null, email, password, String.Empty, true, false, user.CreateDate, user.LastLoginDate, DateTime.MinValue, user.LastPasswordChangedDate, user.LastLockoutDate);
                    status = MembershipCreateStatus.Success;
                    return newUser;
                }
                catch (Exception ex)
                {
                    status = MembershipCreateStatus.ProviderError;
                    log.Error(ex.Message, ex);
                    return newUser;

                }
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            if (password == null || username == null)
            {
                return false;
            }

            LoginUser user = loginUserDao.DaoGetVOById<LoginUser>(username);

            if (user == null)
            {
                return false;
            }
            else
            {
                return (user.Password.Equals(password));
            }

        }

        /// <summary>
        /// 資料來源取得指定成員資格使用者的資訊。如果已指定，則更新使用者的最後活動日期/時間戳記
        /// </summary>
        /// <param name="username">要擷取的使用者名稱。</param>
        /// <param name="userIsOnline">如果 true，則更新指定使用者的最後活動日期/時間戳記</param>
        /// <returns></returns>
        public override MembershipUser GetUser(string username,
         bool userIsOnline)
        {

            LoginUser user = null;
            user = loginUserDao.DaoGetVOById<LoginUser>(username);
            if (user == null)
            {
                return null;
            }
            else
            {
                MembershipUser m = new MembershipUser(this.ToString(), user.UserId, null, user.Email, user.PasswordQuestion, user.Comment, user.IsApproved, user.IsLockedOut, user.CreateDate, user.LastLoginDate, user.LastLoginDate, user.LastPasswordChangedDate, user.LastLockoutDate);

                return m;
            }
        }


        public override MembershipUser GetUser(object providerUserKey,
            bool userIsOnline)
        {
            throw new NotSupportedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            LoginUser user = null;
            user = loginUserDao.GetVOByEmail(email);
            if (user == null)
            {
                return null;
            }
            else
            {
                return user.Email;
            }
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex,
            int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotSupportedException();
        }

        public override bool ChangePassword(string username,
            string oldPassword, string newPassword)
        {
            LoginUser user = null;
            user = loginUserDao.DaoGetVOById<LoginUser>(username);
            if (user == null)
            {
                return false;
            }
            else
            {
                if (!oldPassword.Equals(user.Password))
                {
                    return false;
                }
                else
                {
                    user.Password = newPassword;
                    user.LastPasswordChangedDate = DateTime.Now;
                    loginUserDao.DaoUpdate(user);
                    return true;
                }

            }
        }

        public override bool
            ChangePasswordQuestionAndAnswer(string username,
            string password, string newPasswordQuestion,
            string newPasswordAnswer)
        {
            LoginUser user = null;
            user = loginUserDao.DaoGetVOById<LoginUser>(username);
            if (user == null)
            {
                return false;
            }
            else
            {
                if (!password.Equals(user.Password))
                {
                    return false;
                }
                else
                {
                    user.PasswordQuestion = newPasswordQuestion;
                    user.PasswordAnswer = newPasswordAnswer;
                    loginUserDao.DaoUpdate(user);
                    return true;
                }

            }
        }

        public override bool DeleteUser(string username,
            bool deleteAllRelatedData)
        {
            throw new NotSupportedException();
        }

        public override MembershipUserCollection
            FindUsersByEmail(string emailToMatch, int pageIndex,
            int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override MembershipUserCollection
            FindUsersByName(string usernameToMatch, int pageIndex,
            int pageSize, out int totalRecords)
        {
            throw new NotSupportedException();
        }

        public override string GetPassword(string username, string answer)
        {
            LoginUser user = null;
            user = loginUserDao.DaoGetVOById<LoginUser>(username);
            if (user == null)
            {
                return null;
            }
            else
            {
                if (!answer.Equals(user.PasswordAnswer))
                {
                    return null;
                }
                else
                {
                    return user.Password;
                }
            }
        }


        public override bool EnablePasswordReset
        {
            get { return false; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return true; }
        }
        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }
        public override bool RequiresUniqueEmail
        {
            get { return false; }
        }

        public override string ApplicationName
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }


        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotSupportedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotSupportedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotSupportedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotSupportedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotSupportedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotSupportedException(); }
        }






        public override string ResetPassword(string username,
            string answer)
        {
            throw new NotSupportedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotSupportedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotSupportedException();
        }
    }
}